package scatter.wwd.rest.componentimpl.authority;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.area.rest.service.IAreaService;
import scatter.common.LoginUser;
import scatter.common.dict.PublicDictEnums;
import scatter.common.rest.monitor.MonitorTool;
import scatter.dict.pojo.po.Dict;
import scatter.dict.rest.service.IDictService;
import scatter.identifier.pojo.po.Identifier;
import scatter.identifier.rest.service.IIdentifierService;
import scatter.usersimple.pojo.po.UserSimple;
import scatter.usersimple.rest.service.IUserSimpleService;
import scatter.wwd.pojo.login.WwdAppLoginUser;
import scatter.wwd.pojo.po.UserInfo;
import scatter.wwd.rest.service.IUserInfoService;
import scatter.wxminiapp.pojo.login.WxMaLoginUser;
import scatter.wxminiapp.pojo.po.WxMaUser;
import scatter.wxminiapp.rest.security.WxMiniappUserDetailsServiceListener;
import scatter.wxmp.pojo.po.WxMpUser;

import java.util.Optional;

/**
 * <p>
 * 小程序登录添加用户
 * </p>
 *
 * @author yangwei
 * @since 2022-04-01 21:30
 */
@Service
public class WxMiniappUserDetailsServiceListenerImpl implements WxMiniappUserDetailsServiceListener {

	@Autowired
	private IIdentifierService iIdentifierService;
	@Autowired
	private IUserSimpleService iUserSimpleService;
	@Autowired
	private IUserInfoService iUserInfoService;

	@Autowired
	private IDictService iDictService;
	@Autowired
	private IAreaService iAreaService;


	@Override
	public LoginUser onUserInfoReady(WxMaJscode2SessionResult session, WxMaUser maUser, String appId, WxMaLoginUser wxMaLoginUser) {
		Identifier byIdentifier = iIdentifierService.getByIdentifier(maUser.getOpenId());

		boolean isNewUser = false;
		if (byIdentifier == null) {
			// 不存在添加
			byIdentifier = addByWxMaUser(maUser);
			isNewUser = true;
		}
		UserSimple byId = iUserSimpleService.getById(byIdentifier.getUserId());
		//性别取用户信息字段
		UserInfo userInfo = iUserInfoService.getByUserId(byId.getId());
		if (userInfo!=null) {
			byId.setGenderDictId(userInfo.getGenderDictId());
		}

		Dict genderDict = null;
		if (StrUtil.isNotEmpty(byId.getGenderDictId())) {
			genderDict = iDictService.getById(byId.getGenderDictId());
		}
		String gender = Optional.ofNullable(genderDict).map(Dict::getValue).orElse(null);

		WwdAppLoginUser wwdAppLoginUser = new WwdAppLoginUser(); //LoginMapStruct.INSTANCE.map(wxMpLoginUser);
		wwdAppLoginUser.setUser(byId);
		wwdAppLoginUser.setUserIdentifier(byIdentifier);
		wwdAppLoginUser.addAuthority(wxMaLoginUser.getStringAuthorities());
		wwdAppLoginUser.addAuthority("appclient");
		// 将性别添加到当前登录用户
		wwdAppLoginUser.setGender(gender);
		wwdAppLoginUser.setGender(Optional.ofNullable(genderDict).map(Dict::getValue).orElse(null));

		if (isNewUser) {
			// 新用户注册监控
			MonitorTool.count("wwd.newuser.registry","汪汪队小程序新用户注册",
					"appCode", maUser.getAppCode(),
					"gender", Optional.ofNullable(genderDict).map(Dict::getValue).orElse("none"),
					"city", Optional.ofNullable(maUser.getCityName()).orElse("none")
			);
		}

		return wwdAppLoginUser;
	}

	@Override
	public LoginUser onUserInfoReady(WxMaPhoneNumberInfo phoneNoInfo, WxMaUser maUser, String appId, WxMaLoginUser wxMaLoginUser) {
		Identifier byIdentifier = iIdentifierService.getByIdentifier(phoneNoInfo.getPurePhoneNumber());

		boolean isNewUser = false;
		if (byIdentifier == null) {
			// 不存在添加
			byIdentifier = addByWxMaUser(maUser);
			isNewUser = true;
		}
		UserSimple byId = iUserSimpleService.getById(byIdentifier.getUserId());
		//性别取用户信息字段
		UserInfo userInfo = iUserInfoService.getByUserId(byId.getId());
		if (userInfo!=null) {
			byId.setGenderDictId(userInfo.getGenderDictId());
		}

		Dict genderDict = null;
		if (StrUtil.isNotEmpty(byId.getGenderDictId())) {
			genderDict = iDictService.getById(byId.getGenderDictId());
		}
		String gender = Optional.ofNullable(genderDict).map(Dict::getValue).orElse(null);

		WwdAppLoginUser wwdAppLoginUser = new WwdAppLoginUser(); //LoginMapStruct.INSTANCE.map(wxMpLoginUser);
		wwdAppLoginUser.setUser(byId);
		wwdAppLoginUser.setUserIdentifier(byIdentifier);
		wwdAppLoginUser.addAuthority(wxMaLoginUser.getStringAuthorities());
		wwdAppLoginUser.addAuthority("appclient");
		// 将性别添加到当前登录用户
		wwdAppLoginUser.setGender(gender);
		wwdAppLoginUser.setGender(Optional.ofNullable(genderDict).map(Dict::getValue).orElse(null));

		if (isNewUser) {
			// 新用户注册监控
			MonitorTool.count("wwd.newuser.registry","汪汪队小程序手机号新用户注册",
					"appCode", maUser.getAppCode(),
					"gender", Optional.ofNullable(genderDict).map(Dict::getValue).orElse("none"),
					"city", Optional.ofNullable(maUser.getCityName()).orElse("none")
			);
		}

		return wwdAppLoginUser;	}



	/**
	 * 添加用户信息
	 * @param mpUser
	 * @return
	 */
	public Identifier addByWxMaUser(WxMaUser mpUser) {

		// 添加 wwd 用户信息
		UserSimple user = new UserSimple();
		user.setNickname(mpUser.getNickname());
		user.setGenderDictId(mpUser.getGenderDictId());
		user.setIsLock(false);
		user.setAvatar(mpUser.getAvatar());
		user.setGroupFlag(PublicDictEnums.UserGroupFlagDictItem.wx_mini.name());
		iUserSimpleService.save(user);

		// 添加用户登录标识信息
		Identifier userIdentifier = new Identifier();
		userIdentifier.setUserId(user.getId());
		userIdentifier.setIdentifier(mpUser.getOpenId());
		userIdentifier.setIdentityTypeDictId(iDictService.getIdByGroupCodeAndValue(Identifier.TypeDictGroup.account_type.groupCode(),Identifier.TypeDictItem.wx_ma_mobile.itemValue()));
		userIdentifier.setIsLock(false);
		userIdentifier.setIsExpired(false);
		userIdentifier.setIsDisabled(false);
		userIdentifier.setGroupFlag(PublicDictEnums.UserGroupFlagDictItem.wx_mini.name());
		iIdentifierService.save(userIdentifier);

		// 添加用户详细信息
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(user.getId());
		userInfo.setGenderDictId(mpUser.getGenderDictId());
		userInfo.setNickname(mpUser.getNickname());
		userInfo.setName(mpUser.getNickname());
		userInfo.setPicUrl(StrUtil.nullToEmpty(mpUser.getAvatar()));
		userInfo.setIsHasCar(false);
		userInfo.setIsHasHourse(false);
		userInfo.setIsVerified(false);
		userInfo.setIsShowInList(false);
		iUserInfoService.save(userInfo);

		// 小程序登录不需要添加密码信息

		return userIdentifier;
	}
}
